package www.cskaoyan.com.dao.JDBCUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;


public class JDBCLoad {
    static String url;
    static String username;
    static String password;
    static String driver;


    // 初始化配置
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("jdbc.properties"));// 加载配置文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driver = properties.getProperty("driver");
    }

    // 获取数据库连接
    public static Connection getConnection(){
        Connection connection = null;

        try {
            Class.forName(driver);// 注册驱动
            connection = DriverManager.getConnection(url,username,password);// 获得连接

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }


    // 关闭数据库连接
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if (resultSet != null) resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
